#!/bin/sh
# Created on 2010-05-27 by Jimmy Wu
# Reads matrix files, solves them using the available algorithms,
# and prints the results in a format suitable for a text-based
# data table, 1 GSS per row.
#
# Depends on the existence of *.genparam files for some info
# such as generator type and segnum
# IMPORTANT ASSUMPTION: 
#   Matrix files with the same prefix have the same paramaters.
#   In particular they share the same generator and segnum.
#
# Solver dependencies: the following names must exist in PATH
#   greedy
#   ilp (local command to run ilp.sh <mathematica .m file>)
#
# Row format:
#   Generator Segnum ILP G1 (sc) G2 (vc) G3 (ivc)
#
# Output goes to stdout. Use I/O redirection to save the results.

usage () {
    echo "Usage: $(basename $0) matrix_file ..."
    echo "	Make sure greedy and ilp are in your path, and that"
    echo "	ilp is aliased to 'ilp.sh path_to_mathematic_.m_file'"
}

# Arguments: matrix_file
# output: ILP G1 G2 G3
run_algorithms() {
    # local variable, NOT the same as the global matrix
    local matrix="$1"

    # run in background for parallelization, maybe faster this way
    eval $(echo g1=$(greedy n sc < "$matrix") &
	   echo g2=$(greedy n vc < "$matrix") &
	   echo g3=$(greedy n ivc < "$matrix") &
	   echo g4=$(greedy n isc < "$matrix") &
	   echo ilp=$(ilp "$matrix") & )

    # return output
    echo $ilp $g1 $g2 $g3 $g4
}

if [ -z "$1" ] ; then
    usage >&2
    exit 1
fi

# unnecessary declarations
prefix=""
segnum=""
generator=""
#vertex=Vertex
#segment=Segment
unknown=Unknown

for matrix; do
    if [ "${matrix%-*}" != "$prefix" ] ; then
	# new prefix, read in data
	prefix="${matrix%-*}"
	paramsfile="$prefix".genparam
	if [ -r "$paramsfile" ] && [ -s "$paramsfile" ] ; then
	    read generator segnum params < "$paramsfile"
	else
	    echo "Warning: $paramsfile unusable." >&2
	    segnum=$( head -n1 "$matrix" | tr -d '[:space:]' | wc -m )
	    generator=$unknown
	fi
    fi
    vertexnum=$(wc -l < "$matrix")
    deg2num=$(grep -c '^[^1]*1[^1]*1[^1]*$' "$matrix")

    echo "$matrix $generator $segnum $vertexnum $deg2num $(run_algorithms $matrix)"
done

